import sys
import config
from Tray import TrayIconApp
from window1 import window1
from wifiauthtool import sendreq
from PyQt5.QtWidgets import QApplication, QMainWindow,QMessageBox
from main_ui import Ui_MainWindow
from PyQt5.QtGui import QIcon
class MainWindow(QMainWindow):
    isauto = False
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.setFixedSize(362, 257)
        self.ui.setupUi(self)

        self.ui.Button_login.clicked.connect(self.on_login_clicked)
        self.ui.Button_flux.clicked.connect(self.towindow1)

        toml = config.gtoml()
        self.ui.text_username.setText(toml['setting']['name'])
        self.ui.text_password.setText(toml['setting']['password'])
        self.ui.checkBox1.setChecked(toml['setting']['autologin'])
    def closeEvent(self, event):
        event.accept()
        exit()

    
    def towindow1(self):
        
        self.window1 = window1()
        t.win = self.window1
        self.window1.show()
        self.hide()
    def on_login_clicked(self):
        # 在这里编写按钮点击时的处理逻辑
        username = self.ui.text_username.text()
        password = self.ui.text_password.text()
        toml = config.gtoml()
        toml['setting']['name'] = username
        toml['setting']['password'] = password
        toml['setting']['autologin'] = self.ui.checkBox1.isChecked() 
        config.wtoml(toml)
        if wifi_auth(username,password,self.isauto) == 1:
            self.hide()
            self.towindow1()
            #self.close()
        
def wifi_logout():
    print(f"注销返回：{sendreq("opr=logout&ipv4or6=")}")
def wifi_auth(username,password,isauto):
    go = 0
    wifi_logout()#切换不同账户时需要先注销
    msg = sendreq(f"opr=pwdLogin&userName={username}&pwd={password}&ipv4or6=&rememberPwd=1")
    if msg.find("logon success")!= -1 or msg.find("已在线")!=-1:
        ret ="登陆成功"
        go = 1
    elif msg.find("NOAUTH")!=-1:
        ret = "无限流时间"
        go = 1
    elif msg.find("冻结") != -1:
        ret = "登陆失败，登录频繁，账户被冻结一分钟"
    elif msg == "error":
        ret = "登陆失败，可能是未连接校园网，或者是校园网和流量同时打开导致无法认证"
    else:
        ret = "登陆失败，可能是密码错误"
    if not isauto or go == 0:   
        QMessageBox.information(None, "登陆结果", ret)
    print(msg)

    return go

print("程序启动")
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
main_window = MainWindow()
main_window.show()
t = TrayIconApp(QIcon("favicon.ico"))
t.mainwin = main_window
if main_window.ui.checkBox1.isChecked():
    main_window.isauto = True
    main_window.on_login_clicked()
app.exec_()